//
//  JQFYBuyTicketInfoViewController.m
//  JQFY
//
//  Created by 代辉 on 2017/9/22.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYBuyTicketInfoViewController.h"
#import "JQFYTicketPayTableViewCell.h"
#import "JQFYPayTypeVC.h"
#import "JQFYBuyTicketListModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import "JQFYUserData.h"
#import "JQFYBannerViewController.h"
#import "JQFYTicketInfo_BuyModel.h"
#import "JQFYMyShowController.h"
#import "WXApi.h"

@interface JQFYBuyTicketInfoViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *ticketInfoTableView;
@property (nonatomic,strong) JQFYPayTypeVC *payTypeVC;
@property (nonatomic,strong) UIPageControl *pageCtr;
@property (nonatomic,strong) JQFYTicketPayTableViewCell *currentCell;
@property (nonatomic,strong) NSArray <JQFYTicketInfo_BuyModel *>*ticketInfoModel;
@property (nonatomic,weak) UILabel *numLabel;
@property (nonatomic,weak) UILabel *payMoneyLabel;
@property (nonatomic,weak) UILabel *money;
@property (nonatomic,assign) NSInteger selRow;
@property (nonatomic,copy) NSString *orderStr;

@end
static NSString *ticketInfoTableViewCell = @"ticketInfoTableViewCell";
@implementation JQFYBuyTicketInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupNavInfo];
    [self setupUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucess) name:@"paySucess" object:nil];
    self.currentCell = nil;
}
#pragma mark - 支付成功返回界面 -
- (void)paySucess
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isPop"]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isPop"];
        return;
    }
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isBuy"];
    self.numLabel.text = @"0";
    self.payMoneyLabel.text =@"0";
    self.ticketInfoModel[self.selRow].ticketNumber = 0;
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.view layoutIfNeeded];
    [self tableView:self.ticketInfoTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
}
- (UITableView *)ticketInfoTableView
{
    if (_ticketInfoTableView == nil) {
        _ticketInfoTableView = [[UITableView alloc] init];
        _ticketInfoTableView.dataSource = self;
        _ticketInfoTableView.delegate = self;
        _ticketInfoTableView.showsHorizontalScrollIndicator = NO;
        _ticketInfoTableView.showsVerticalScrollIndicator = NO;
        _ticketInfoTableView.tableFooterView = [UIView new];
        _ticketInfoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_ticketInfoTableView registerClass:[JQFYTicketPayTableViewCell class] forCellReuseIdentifier:ticketInfoTableViewCell];
        _ticketInfoTableView.rowHeight = UITableViewAutomaticDimension;
        _ticketInfoTableView.estimatedRowHeight = 100;
    }
    return _ticketInfoTableView;
}
- (void)setupNavInfo
{
    self.navigationItem.title = @"购票信息";
    UIFont *font = [UIFont fontWithName:@"Verdana-Bold" size:15 *SCAL];
    NSDictionary *dic = @{NSFontAttributeName:font,
                          NSForegroundColorAttributeName: [UIColor whiteColor]};
    self.navigationController.navigationBar.titleTextAttributes =dic;
    UIImage *leftImg = [UIImage imageNamed:@"ticketInfo_back"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImg style:UIBarButtonItemStylePlain target:self action:@selector(didClickBack)];
}

- (void)setupUI
{
    // 票类 tableView
    [self.view addSubview:self.ticketInfoTableView];
    self.ticketInfoTableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.ticketInfoTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(25 *SCAL);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(160 *SCAL);
    }];
    
    UIImageView *rmb = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"RMB"]];
    [self.view addSubview:rmb];
    [rmb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20 *SCAL);
        make.top.equalTo(_ticketInfoTableView.mas_bottom).offset(22 *SCAL);
    }];
    UILabel *money = [UILabel new];
    money.font = [UIFont fontWithName:@"BebasNeue" size:45];
    money.text = @"0";
    [self.view addSubview:money];
    [money mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(rmb.mas_right).offset(20 *SCAL);
        make.bottom.equalTo(rmb).offset(14 *SCAL);
    }];
    
    UIButton *addButton = [UIButton new];
    [addButton setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addButton];
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-20 *SCAL);
        make.bottom.equalTo(rmb);
    }];
    
    UILabel *numLabel = [UILabel new];
    numLabel.text = @"0";
    numLabel.textAlignment = NSTextAlignmentCenter;
    numLabel.font = [UIFont fontWithName:@"BebasNeue" size:30];
    [self.view addSubview:numLabel];
    [numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(addButton.mas_left);
        make.width.mas_equalTo(40 *SCAL);
        make.bottom.equalTo(addButton).offset(7 *SCAL);
    }];
//    minus
    UIButton *minus = [UIButton new];
    [minus setBackgroundImage:[UIImage imageNamed:@"minus"] forState:UIControlStateNormal];
    [minus addTarget:self action:@selector(minus:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:minus];
    [minus mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(numLabel.mas_left);
        make.bottom.equalTo(rmb);
    }];
    
    UILabel *payMoneyLabel = [UILabel new];
    payMoneyLabel.text = @"0";
    payMoneyLabel.textAlignment = NSTextAlignmentCenter;
    payMoneyLabel.textColor = [UIColor colorWithHex:0x9757EC];
    payMoneyLabel.font = [UIFont fontWithName:@"BebasNeue" size:45];
    [self.view addSubview:payMoneyLabel];
    [payMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(addButton).offset(55 *SCAL);
    }];
    
    UIImageView *amountImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"总计（合并）"]];
    [self.view addSubview:amountImage];
    [amountImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(payMoneyLabel);
        make.top.equalTo(payMoneyLabel.mas_bottom).offset(-5 *SCAL);
    }];
    
    UICollectionViewFlowLayout *flowLyout = [UICollectionViewFlowLayout new];
    flowLyout.itemSize = CGSizeMake(DH_Screen_Width, 110 *SCAL);
    flowLyout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLyout.minimumLineSpacing = 0;
    flowLyout.minimumInteritemSpacing = 0;
    self.payTypeVC = [[JQFYPayTypeVC alloc] initWithCollectionViewLayout:flowLyout];
    [self addChildViewController:self.payTypeVC];
    [self.view addSubview:self.payTypeVC.view];
    [self.payTypeVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(amountImage.mas_bottom).offset(20 *SCAL);
        make.height.mas_equalTo(110 *SCAL);
        make.left.right.equalTo(self.view);
    }];
    
    [self.view addSubview:self.pageCtr];
    [_pageCtr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.payTypeVC.view.mas_bottom);
    }];
    
    __weak typeof(self) weakSelf = self;
    self.payTypeVC.offsetX = ^(NSUInteger num) {
        
        weakSelf.pageCtr.currentPage = num;
    };
    
    UIButton *payButton = [UIButton new];
    [self.view addSubview:payButton];
    [payButton setBackgroundImage:[UIImage imageNamed:@"确认并支付（合并）"] forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(pay) forControlEvents:UIControlEventTouchUpInside];
    [payButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-30 *SCAL);
    }];
    UIButton *userReadBtn = [UIButton new];
    [self.view addSubview:userReadBtn];
    [userReadBtn setBackgroundImage:[UIImage imageNamed:@"点击确认并支付表示已阅读《用户须知》并同意"] forState:UIControlStateNormal];
    [userReadBtn addTarget:self action:@selector(didCleckBtn) forControlEvents:UIControlEventTouchUpInside];
    [userReadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(payButton.mas_top).offset(-10 *SCAL);
    }];
    
    self.numLabel = numLabel;
    self.payMoneyLabel = payMoneyLabel;
    self.money = money;
}
- (void)didCleckBtn
{
    JQFYBannerViewController *userRead = [JQFYBannerViewController new];
    WKWebView *web = [[WKWebView alloc] initWithFrame:userRead.view.bounds];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://app.uninhibited.cn/plan/user_notes.html"]]];
    [userRead.view addSubview:web];
    [self.navigationController pushViewController:userRead animated:YES];
}

#pragma mark - 点击加号Action -
- (void)add:(UIButton *)btn
{
    if ([self.ticketInfoModel[self.selRow].amount integerValue] == 0) {
        MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeCustomView;
        hud.removeFromSuperViewOnHide = YES;
        hud.detailsLabelText = @"已售空";
        [hud hide:YES afterDelay:1];
        return;
    }
    self.ticketInfoModel[self.selRow].ticketNumber += 1;
    if (self.ticketInfoModel[self.selRow].ticketNumber >= [self.ticketInfoModel[self.selRow].amount integerValue]) {
        self.ticketInfoModel[self.selRow].ticketNumber = [self.ticketInfoModel[self.selRow].amount integerValue];
    }
    [self priceChangeWith:self.selRow];
}

#pragma mark - 点击减号 -
- (void)minus:(UIButton *)btn
{
    if (self.ticketInfoModel[self.selRow].ticketNumber == 0) {
        return;
    }
    self.ticketInfoModel[self.selRow].ticketNumber -= 1;
    [self priceChangeWith:self.selRow];
}
#pragma mark - 点击用户须知 -
- (void)read
{
    JQFYBannerViewController *banner = [JQFYBannerViewController new];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:banner.view.bounds];
    NSURL *url = [NSURL URLWithString:@"http://app.uninhibited.cn/plan/user_notes.html"];
    if (url != nil) {
        [webView loadRequest:[NSURLRequest requestWithURL:url]];
    }
    [banner.view addSubview:webView];
    [self.navigationController pushViewController:banner animated:YES];
}

#pragma mark - 支付 -
- (void)pay
{
    if (self.ticketInfoModel[self.selRow].ticketNumber == 0) {
        MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeCustomView;
        hud.removeFromSuperViewOnHide = YES;
        hud.detailsLabelText = @"至少选择一种票";
        [hud hide:YES afterDelay:1];
        return;
    }
    NSString *ticket_amount = [NSString stringWithFormat:@"%zd",[self.ticketInfoModel[self.selRow].price integerValue] * self.ticketInfoModel[self.selRow].ticketNumber];
    NSDictionary *dict = @{
                           @"token":[JQFYUserData userDataInSandbox].token,
                           @"buy_id":self.ticketInfoModel[self.selRow].buy_id,
                           @"total_amount":ticket_amount,
                           @"ticket_amount":[NSString stringWithFormat:@"%zd",self.ticketInfoModel[self.selRow].ticketNumber],
                           };
    if (self.pageCtr.currentPage == 0) {
        
        [__Pay__ aliPay:dict success:^{
            [self paySucess];
        }];
        
    } else {
        
        [__Pay__ wxPay:dict];
        
    }
}

#pragma mark - pageControll -
- (UIPageControl *)pageCtr
{
    if (_pageCtr == nil) {
        _pageCtr = [UIPageControl new];
        _pageCtr.numberOfPages = 2;
        _pageCtr.currentPage = 0;
        [_pageCtr setValue:[UIImage imageNamed:@"page_current"] forKey:@"_currentPageImage"];
        [_pageCtr setValue:[UIImage imageNamed:@"page_img"] forKey:@"_pageImage"];
       
    }
    return _pageCtr;
}

#pragma mark - UITableViewDataSource -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.ticketInfoModel.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JQFYTicketPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ticketInfoTableViewCell forIndexPath:indexPath];
    cell.ticket_info = self.ticketInfoModel[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    JQFYTicketPayTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell == self.currentCell) {
        return;
    }
    if (self.currentCell) {
        self.currentCell.selectImageView.hidden = YES;
        self.currentCell.titleColor = [UIColor blackColor];
    }
    cell.selectImageView.hidden = NO;
    cell.titleColor = [UIColor whiteColor];
    [self priceChangeWith:indexPath.row];
    self.selRow = indexPath.row;
    self.currentCell = cell;
}

- (void)priceChangeWith:(NSInteger)num
{
    self.numLabel.text = [NSString stringWithFormat:@"%zd",self.ticketInfoModel[num].ticketNumber];
    self.money.text = self.ticketInfoModel[num].price;
    
    self.payMoneyLabel.text = [NSString stringWithFormat:@"%zd",[self.ticketInfoModel[num].price integerValue] * self.ticketInfoModel[num].ticketNumber];
}
- (void)setListModel:(JQFYActivityListModel *)listModel
{
    _listModel = listModel;
    self.ticketInfoModel = listModel.start_time.firstObject.ticket;
    [self.ticketInfoTableView reloadData];
}
- (void)didClickBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
